<template>
        <div>
            <el-button type="danger" size="small" @click="patchDelete">批量删除</el-button>
            <el-button type="primary" size="small" @click="router.push('add')">新增</el-button>
            <el-table :data="userList" stripe style="width:100%;" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="avatar" label="头像">
                    <template #default="data">
                        <el-avatar :size="50"
                            :src="`http://120.76.247.5:2001${data.row.avatar}` || 'https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png'" />
                    </template>
                </el-table-column>
                <el-table-column prop="username" label="用户名" />
                <el-table-column prop="nickname" label="昵称" />
                <el-table-column label="注册时间">
                    <template #default="data">
                        {{ moment(new Date(data.row.regtime)).format("YYYY-MM-DD HH:mm:ss a") }}
                    </template>
                </el-table-column>
                <el-table-column label="最后登录时间">
                    <template #default="data">
                        {{ moment(new Date(data.row.regtime)).format("YYYY-MM-DD HH:mm:ss a") }}
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-popconfirm :title="`确认删除${scope.row.username}?`" @confirm="deleteUser(scope.row._id)">
                            <template #reference>
                                <el-button link type="danger" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                        <el-button link type="primary" @click="router.push(`/manage/user/edit/${scope.row._id}`)" size="small">
                            修改
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination background layout="total,  prev, pager, next,sizes, jumper" :total="page.total"
                @current-change="change" v-model:current-page="page.pagenum" v-model:page-size="page.pagesize"
                :page-sizes="[5, 10, 15, 20]" :small="true" :disabled="false" />
        </div>
</template>
  <!-- <script>
  export default{
    async setup(){
        await http.get("/xxx")
    }
  }
  </script> -->
<script setup>
import http from '@/utils/http'
import { reactive, ref, watchEffect } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import moment from 'moment'
let router = useRouter();
let route = useRoute();
let routepagenum = parseInt(route.query.page) || 1;
let userList = ref([]);//手动解包 .value
let page = reactive({
    pagesize: 5, //存储的是 每页显示条数 每页显示5条数据
    total: 0,
    pagenum: routepagenum //存储当前页码数 1 2 3 4
});
async function getUserList() {
    let re = await http.get("/user", { params: { size: page.pagesize, page: page.pagenum } });
    userList.value = re.result; //可以重新赋值
    page.total = re.total;
}
//在setup 语法糖里面 默认代码块里面如果有 异步代码，那么这个组件就默认是异步组件
// watch  和 watchEffect 有什么区别？？？除了懒侦听以外还有什么区别？？？
watchEffect(async () => {
    getUserList();
    // console.log(userList);
});
let change = pagenum => {
    page.pagenum = pagenum;
    // router.push('list?page=3');//编程式导航
    //点击页数的时候 跳转路由并传参 query传值 地址栏传值 动态
    router.push({ path: "list", query: { page: pagenum } });
}
let sizeChange = (e) => {
    console.log("eve==>", e);
}
let checkUsers = ref([]);
let handleSelectionChange = (vals) => {
    // console.log('选择的数据===>',vals);
    checkUsers.value = vals.map(t => t._id);
    // console.log(checkUsers.value);
}
let patchDelete = async () => {
    //这里用批量传递数组用data传值 不用params传值
    let re = await http.delete("/user?", { data: { ids: checkUsers.value } })
    //    console.log("删除结果===>",re);
    if (re.deletedCount > 0) {
        ElMessage({
            type: "success",
            message: `删除了${re.deletedCount}条数据`
        });
        getUserList();
    } else {
        ElMessage({
            type: "error",
            message: "删除失败!"
        })
    }

}
let deleteUser = async (id) => {
    // console.log("确认删除",id)
    let re = await http.delete("/user/" + id);
    console.log("删除结果===>", re);
    if (re.deletedCount) {
        getUserList();
    } else {
        ElMessage({
            type: "error",
            message: "删除失败!"
        })
    }
}
//时间转换函数
// let tranTime = (time, fstr = 'YYYY-mm-dd H:i:s') => {
//     let date = new Date(time);
//     if (!time || time.length < 1) return "";
//     let dmap = {
//         Y: date.getFullYear(),
//         m: date.getMonth() + 1,
//         d: date.getDate(),
//         H: date.getHours(),
//         i: date.getMinutes(),
//         s: date.getSeconds()
//     }
//     for (let key in dmap) {
//         let reg = new RegExp(key + "+", 'ig');
//         fstr = fstr.replace(reg, dmap[key]);
//     }
//     return fstr;
// }
</script>
<style lang="scss" scoped>
.v-enter-from {
    transform: translateX(-100%);
}
.v-enter-to {
    transform: translateX(0%);
}
.v-enter-active {
    transition: all 0.5s linear;
}
</style>